import Toast from "../popups/Toast";
import Config from "../entity/Config";
import {clearConfigs, getConfig} from "../entity/ConfigHelper";
import Wx from "../../framework/wx/Wx";

/**
 * 个人版本配置控制器.
 *
 */
export class PrivateConfig extends Config {

    // 清除本地数据的标记. 通过对比seq是否变化来区分是否需要清除本地数据.
    public readonly clearFlag: { seq: number, keys: string[] } = {seq: 0, keys: []};

    private inviteState: { [key: number]: number; } = {};

    constructor() {
        super("private_cfg");
    }

    public onSynced(success: boolean, oldData: PrivateConfig, upload: boolean) {
        if (oldData.clearFlag && this.clearFlag
            && this.clearFlag.seq != 0 && oldData.clearFlag.seq != 0
            && this.clearFlag.seq != oldData.clearFlag.seq) {
            console.warn("检测到个人数据清除标记,开始清除数据.");
            Toast.showToast("需要清除数据,成功清除后程序将自动退出.");
            clearConfigs(this.clearFlag.keys).then(() => {
                cc.log("数据擦除成功,程序退出.");
                Wx.exit();
            })
        } else {
            cc.log("无需清除个人数据");
        }
    }

    public getinvites() {
        return this.inviteState;
    }

    public getinvite(index: number): number {
        return this.inviteState[index] || 0;
    }

    public setInviteState(index: number, state: number) {
        this.inviteState[index] = state;
        this.save();
    }

    //
    // public clear(): Promise<any> {
    //     return Promise.resolve();
    // }
}

export const privateConfig: PrivateConfig = getConfig(PrivateConfig);